package tenumn.energytech.registrys.machine.heart;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import tenumn.energytech.registrys.CapabilitiesRegistry;
import tenumn.energytech.registrys.capability.CapabilityHeart;
import tenumn.energytech.registrys.machine.MachineBlockEntity;

public class SolarHeaterBlockEntity extends MachineBlockEntity {
    private final CapabilityHeart heart;
    public SolarHeaterBlockEntity(BlockEntityType<?> pType, BlockPos pWorldPosition, BlockState pBlockState) {
        super(pType, pWorldPosition, pBlockState);
        heart=new CapabilityHeart();
    }

    @NotNull
    @Override
    public <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
        if(cap== CapabilitiesRegistry.HEART_CAPABILITY&&side==Direction.DOWN)
            return LazyOptional.of(()->heart).cast();
        return super.getCapability(cap, side);
    }

    @Override
    protected void saveAdditional(CompoundTag pTag) {
        pTag.put("Heart",heart.serializeNBT());
        super.saveAdditional(pTag);
    }

    @Override
    public void load(CompoundTag pTag) {
        heart.deserializeNBT(pTag.getCompound("Heart"));
        super.load(pTag);
    }

    @Override
    public void tick() {
        if(level instanceof ServerLevel serverLevel){
                BlockEntity blockEntity = serverLevel.getBlockEntity(getBlockPos().below());
                if (blockEntity != null)
                    blockEntity.getCapability(CapabilitiesRegistry.HEART_CAPABILITY,Direction.UP)
                            .ifPresent(otherHeart -> {
                                otherHeart.rise(heart.coolDown(10, false), false);
                            });

            if(!level.isRainingAt(getBlockPos())&&level.isDay()){
                heart.rise(1,false);
                level.blockEntityChanged(getBlockPos());
            }
        }
    }
}
